<template>
  <div class="material-library-container">
    <div class="page-header">
      <h2>素材库</h2>
      <p class="page-description">管理和查看与好友的问答记录</p>
    </div>

    <!-- 筛选区域 -->
    <div class="filter-section">
      <el-card>
        <div class="filter-content">
          <!-- 搜索框 -->
          <div class="filter-item">
            <label>搜索问答：</label>
            <el-input
              v-model="searchQuery"
              placeholder="搜索问答内容"
              size="default"
              style="width: 300px;"
              clearable
              @input="handleSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </div>

          <!-- 模板选择 -->
          <div class="filter-item">
            <label>选择模板：</label>
            <el-select 
              v-model="selectedTemplate" 
              placeholder="选择模板" 
              size="default"
              @change="handleTemplateChange"
              style="width: 200px;"
              clearable
            >
              <template #prefix>
                <el-icon><Document /></el-icon>
              </template>
              <el-option
                v-for="template in templateOptions"
                :key="template"
                :label="template"
                :value="template"
              />
            </el-select>
          </div>

          <!-- 操作按钮 -->
          <div class="filter-item">
            <el-button type="primary" @click="refreshQaList" :loading="qaLoading">
              <el-icon><Refresh /></el-icon>
              刷新
            </el-button>
            <el-button type="success" @click="openAddDialog">
              <el-icon><Plus /></el-icon>
              新增问答
            </el-button>
            <el-button type="warning" @click="openCreateTemplateDialog">
              <el-icon><Plus /></el-icon>
              创建模板
            </el-button>
            <el-button type="danger" @click="openDeleteDialog">
              <el-icon><Delete /></el-icon>
              删除模板
            </el-button>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 问答列表 -->
    <div class="qa-list-section">
      <el-card>
        <template #header>
          <div class="card-header">
            <span>问答列表</span>
            <span class="qa-count">共 {{ filteredQaList.length }} 条记录</span>
          </div>
        </template>

        <div v-if="qaLoading" class="loading-container">
          <el-loading :fullscreen="false">加载中...</el-loading>
        </div>
        <div v-else-if="qaList.length === 0" class="empty-container">
          <el-empty description="暂无问答记录" />
        </div>
        <div v-else class="qa-list-container">
          <el-table :data="paginatedQaList" style="width: 100%" v-loading="qaLoading">
            <el-table-column prop="id" label="ID" width="120" show-overflow-tooltip />
                         <el-table-column label="模板" width="160" show-overflow-tooltip>
              <template #default="scope">
                {{ getQaDisplay(scope.row).category || '-' }}
              </template>
            </el-table-column>
            <el-table-column label="问题" min-width="400" show-overflow-tooltip>
              <template #default="scope">
                {{ getQaDisplay(scope.row).question || '-' }}
              </template>
            </el-table-column>
            <el-table-column label="答案" min-width="400" show-overflow-tooltip>
              <template #default="scope">
                {{ getQaDisplay(scope.row).answer || '-' }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="200" fixed="right">
              <template #default="scope">
                <div class="action-buttons">
                  <el-button type="primary" size="small" @click="handleEdit(scope.row)">
                    <el-icon><Edit /></el-icon>
                    编辑
                  </el-button>
                  <el-button type="danger" size="small" @click="handleDelete(scope.row)">
                    <el-icon><Delete /></el-icon>
                    删除
                  </el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
          
          <!-- 分页组件 -->
          <div class="pagination-container">
            <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :page-sizes="[10, 20, 50, 100]"
              :total="filteredQaList.length"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </div>
      </el-card>
    </div>

    <!-- 新增/编辑问答弹窗 -->
    <el-dialog 
      v-model="editDialogVisible" 
      :title="currentEditingId ? '编辑问答' : '新增问答'" 
      width="600px"
    >
      <el-form :model="qaForm" label-width="80px" :rules="qaFormRules" ref="qaFormRef">
        <el-form-item label="模板" prop="template">
          <el-select 
            v-model="qaForm.template" 
            placeholder="选择模板" 
            style="width: 100%;"
            clearable
          >
            <el-option
              v-for="template in templateOptions"
              :key="template"
              :label="template"
              :value="template"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="问题" prop="question">
          <el-input 
            v-model="qaForm.question" 
            placeholder="请输入问题" 
            type="textarea" 
            :rows="3"
          />
        </el-form-item>
        <el-form-item label="答案" prop="answer">
          <el-input 
            v-model="qaForm.answer" 
            placeholder="请输入答案" 
            type="textarea" 
            :rows="4"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" :loading="editSaving" @click="saveQaForm">保存</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 创建模板弹窗 -->
    <el-dialog 
      v-model="createTemplateDialogVisible" 
      title="创建模板" 
      width="400px"
    >
      <el-form :model="templateForm" label-width="80px" :rules="templateFormRules" ref="templateFormRef">
        <el-form-item label="模板名称" prop="name">
          <el-input 
            v-model="templateForm.name" 
            placeholder="请输入模板名称" 
            clearable
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="createTemplateDialogVisible = false">取消</el-button>
          <el-button type="primary" :loading="templateSaving" @click="saveTemplateForm">创建</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 删除模板弹窗 -->
    <el-dialog 
      v-model="deleteTemplateDialogVisible" 
      title="删除模板" 
      width="400px"
    >
      <el-form :model="deleteTemplateForm" label-width="80px" ref="deleteTemplateFormRef">
        <el-form-item label="选择模板" prop="templateName">
          <el-select 
            v-model="deleteTemplateForm.templateName" 
            placeholder="请选择要删除的模板" 
            style="width: 100%;"
            clearable
          >
            <el-option
              v-for="template in templateOptions"
              :key="template"
              :label="template"
              :value="template"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="deleteTemplateDialogVisible = false">取消</el-button>
          <el-button type="danger" :loading="templateDeleting" @click="confirmDeleteTemplate">确认删除</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Search, 
  Refresh, 
  Plus, 
  Edit, 
  Delete 
} from '@element-plus/icons-vue'
import axios from 'axios'



interface QaItem {
  id: string
  text: string
}

// 响应式数据
const searchQuery = ref('')
const qaList = ref<QaItem[]>([])
const qaLoading = ref(false)

// 模板相关
const selectedTemplate = ref('')
const templateOptions = ref<string[]>([])

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)

// 编辑相关
const editDialogVisible = ref(false)
const editSaving = ref(false)
const currentEditingId = ref('')
const qaFormRef = ref()
const qaForm = reactive({
  question: '',
  answer: '',
  template: ''

})

// 表单验证规则
const qaFormRules = {
  question: [
    { required: true, message: '请输入问题', trigger: 'blur' }
  ],
  answer: [
    { required: true, message: '请输入答案', trigger: 'blur' }
  ],
  template: [
    { required: true, message: '请选择模板', trigger: 'blur'  } 
  ]
}

// 模板创建相关
const createTemplateDialogVisible = ref(false)
const templateSaving = ref(false)
const templateFormRef = ref()
const templateForm = reactive({
  name: ''
})

// 模板删除相关
const deleteTemplateDialogVisible = ref(false)
const templateDeleting = ref(false)
const deleteTemplateFormRef = ref()
const deleteTemplateForm = reactive({
  templateName: ''
})

// 模板表单验证规则
const templateFormRules = {
  name: [
    { required: true, message: '请输入模板名称', trigger: 'blur' }
  ]
}

// 过滤后的问答列表
const filteredQaList = computed(() => {
  let filtered = qaList.value
  
  // 按模板过滤
  if (selectedTemplate.value) {
    filtered = filtered.filter(item => {
      const display = getQaDisplay(item)
      return display.category === selectedTemplate.value
    })
  }
  
  // 按搜索关键词过滤
  if (searchQuery.value) {
    filtered = filtered.filter(item => 
      item.text.toLowerCase().includes(searchQuery.value.toLowerCase())
    )
  }
  
  return filtered
})

// 分页后的问答列表
const paginatedQaList = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredQaList.value.slice(start, end)
})

// 刷新问答列表
const refreshQaList = async () => {
  qaLoading.value = true
  try {
    const response = await axios.get('/v1/rag/all-texts')
    qaList.value = response.data || []
    // 重置分页到第一页
    currentPage.value = 1
  } catch (error) {
    console.error('获取问答列表失败:', error)
    ElMessage.error('获取问答列表失败')
    qaList.value = []
  } finally {
    qaLoading.value = false
  }
}

// 分页处理函数
const handleSizeChange = (val: number) => {
  pageSize.value = val
  currentPage.value = 1 // 重置到第一页
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
}

// 模板相关函数
const handleTemplateChange = () => {
  // 当选择模板时，重置分页到第一页
  currentPage.value = 1
}

// 获取模板列表
const fetchTemplateList = async () => {
  try {
    const response = await axios.get('/conversation/mode')
    templateOptions.value = response.data.data || []
  } catch (error) {
    console.error('获取模板列表失败:', error)
    templateOptions.value = []
  }
}

// 打开创建模板对话框
const openCreateTemplateDialog = () => {
  templateForm.name = ''
  createTemplateDialogVisible.value = true
}

// 打开删除模板对话框
const openDeleteDialog=()=>{
  deleteTemplateForm.templateName = ''
  deleteTemplateDialogVisible.value = true
}

// 确认删除模板
const confirmDeleteTemplate = async () => {
  if (!deleteTemplateForm.templateName) {
    ElMessage.warning('请选择要删除的模板')
    return
  }

  try {
    await ElMessageBox.confirm(`确定要删除模板"${deleteTemplateForm.templateName}"吗？`, '删除确认', {
      type: 'warning',
      confirmButtonText: '确定',
      cancelButtonText: '取消'
    })
  } catch {
    return
  }

  templateDeleting.value = true
  try {
    // 调用后端删除模板接口
    const response = await axios.delete('/conversation/mode', {
      params: {
        template_name: deleteTemplateForm.templateName
      }
    });
    
    if (response.data?.code === 200) {
      ElMessage.success('模板删除成功')
      deleteTemplateDialogVisible.value = false
      // 刷新模板列表
      await fetchTemplateList()
      // 如果当前选中的是被删除的模板，则清空选择
      if (selectedTemplate.value === deleteTemplateForm.templateName) {
        selectedTemplate.value = ''
      }
    } else {
      ElMessage.error(response.data?.msg || '删除失败')
    }
  } catch (error: any) {
    console.error('删除模板失败:', error)
    ElMessage.error('删除失败：' + (error.response?.data?.msg || error.message))
  } finally {
    templateDeleting.value = false
  }
}
// 保存模板表单
const saveTemplateForm = async () => {
  if (!templateFormRef.value) return
  
  try {
    await templateFormRef.value.validate()
  } catch {
    return
  }
  
  templateSaving.value = true
  try {
    const response = await axios.post('/conversation/mode', {}, {
      params: {
        template_name: templateForm.name
      }
    });
    
    if (response.data?.code === 200) {
      ElMessage.success('模板创建成功')
      createTemplateDialogVisible.value = false
      // 刷新模板列表
      await fetchTemplateList()
    } else {
      ElMessage.error(response.data?.msg || '创建失败')
    }
  } catch (error: any) {
    console.error('创建模板失败:', error)
    ElMessage.error('创建失败：' + (error.response?.data?.msg || error.message))
  } finally {
    templateSaving.value = false
  }
}

// 处理搜索
const handleSearch = () => {
  // 搜索功能通过计算属性自动过滤
}

// 打开新增对话框
const openAddDialog = () => {
  currentEditingId.value = ''
  qaForm.question = ''
  qaForm.answer = ''
  qaForm.template = ''
  editDialogVisible.value = true
}

// 编辑问答
const handleEdit = (row: QaItem) => {
  currentEditingId.value = row.id
  // 解析问答内容
  qaForm.question = getQaDisplay(row).question ?? ''
  qaForm.answer = getQaDisplay(row).answer ?? ''
  // 从JSON或文本中解析分类作为模板名（category）
  qaForm.template = getQaDisplay(row).category || ''
  
  editDialogVisible.value = true
}

// 解析问答文本
const parseQaText = (text: string): { question: string; answer: string } => {
  let question = ''
  let answer = ''
  
  // 尝试多种格式解析
  const questionPrefixes = ['问题：', '客户问：', 'Q：', '客户问 ']
  const answerPrefixes = ['回答：', 'A：']
  
  let foundQuestionPrefix: string | null = null
  let foundAnswerPrefix: string | null = null
  let questionStartIndex = 0
  let answerStartIndex = -1

  // 查找问题前缀
  for (const prefix of questionPrefixes) {
    const index = text.indexOf(prefix)
    if (index !== -1) {
      foundQuestionPrefix = prefix
      questionStartIndex = index + prefix.length
      break
    }
  }

  // 查找回答前缀
  if (foundQuestionPrefix) {
    for (const prefix of answerPrefixes) {
      const index = text.indexOf(prefix, questionStartIndex)
      if (index !== -1) {
        foundAnswerPrefix = prefix
        answerStartIndex = index + prefix.length
        break
      }
    }
  }

  // 如果找到问题和回答前缀
  if (foundQuestionPrefix && foundAnswerPrefix && answerStartIndex !== -1) {
    question = text.substring(questionStartIndex, answerStartIndex - foundAnswerPrefix.length)
      .replace(/[，,]/g, '')
      .trim()
    answer = text.substring(answerStartIndex).trim()
  } else {
    // 默认处理
    const textParts = text.split('\n')
    if (textParts.length >= 2) {
      question = textParts[0].replace(/^问题：|^客户问：|^Q：|^客户问 /i, '')
        .replace(/[，,]/g, '')
        .trim()
      answer = textParts.slice(1).join('\n').replace(/^回答：|^A：/i, '').trim()
    } else {
      question = text.replace(/[，,]/g, '').trim()
      answer = ''
    }
  }
  
  return { question, answer }
}

// 提供统一展示结构（兼容JSON与纯文本）
const getQaDisplay = (row: QaItem): { category?: string; source?: string; product_type?: string; question?: string; answer?: string } => {
  try {
    // row.text 若是 JSON 字符串
    const maybeJson = row.text.trim()
    if (maybeJson.startsWith('{') && maybeJson.endsWith('}')) {
      const obj = JSON.parse(maybeJson)
      return {
        category: obj.category,
        source: obj.source,
        product_type: obj.product_type,
        question: obj.question,
        answer: obj.answer
      }
    }
  } catch (e) {
    // 忽略解析错误，走兜底
  }
  // 兜底：从文本中拆出问题/答案
  const { question, answer } = parseQaText(row.text || '')
  return { question, answer }
}

// 保存问答表单
const saveQaForm = async () => {
  if (!qaFormRef.value) return
  
  try {
    await qaFormRef.value.validate()
  } catch {
    return
  }
  
  if (!qaForm.question.trim() || !qaForm.answer.trim()) {
    ElMessage.warning('请填写问题与答案')
    return
  }
  
  editSaving.value = true
  try {
    // 构建格式化文本
    const formattedQuestion = `${qaForm.question}`
    const formattedAnswer = `${qaForm.answer}`
    
    if (currentEditingId.value) {
      // 更新操作
      await axios.post('/v1/rag/update-text', {
        doc_id: currentEditingId.value,
        questions:[qaForm.question],
        answers:[qaForm.answer],
        category: qaForm.template
        // texts: [combinedText]
      })
      ElMessage.success('问答更新成功')
    } else {
      // 新增操作
      const payload = {
        questions: [formattedQuestion],
        answers: [formattedAnswer],
        template_name: qaForm.template || undefined
      }
      
      const res = await axios.post('/conversation/update', payload)
      if (res.data?.code === 200) {
        ElMessage.success('保存成功')
      } else {
        ElMessage.error(res.data?.msg || '保存失败')
      }
    }
    
    editDialogVisible.value = false
    await refreshQaList()
  } catch (error: any) {
    console.error('保存失败:', error)
    ElMessage.error('操作失败：' + (error.response?.data?.msg || error.message))
  } finally {
    editSaving.value = false
  }
}

// 删除问答
const handleDelete = async (row: QaItem) => {
  try {
    await ElMessageBox.confirm('确定要删除这条问答吗？此操作不可恢复', '删除确认', {
      type: 'warning',
      confirmButtonText: '确定',
      cancelButtonText: '取消'
    })
  } catch {
    return
  }
  
  try {
    const res = await axios.post('/v1/rag/del-texts', { doc_ids: [row.id] })
    
    if (res.data?.code === 200) {
      ElMessage.success('删除成功')
      await refreshQaList()
    } else {
      ElMessage.error(res.data?.msg || '删除失败')
    }
  } catch (error: any) {
    console.error('删除失败:', error)
    ElMessage.error('删除失败：' + (error.response?.data?.msg || error.message))
  }
}

// 页面加载时初始化
onMounted(async () => {
  await Promise.all([
    refreshQaList(),
    fetchTemplateList()
  ])
})
</script>

<style scoped lang="scss">
.material-library-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 120px);

  .page-header {
    margin-bottom: 20px;
    
    h2 {
      margin: 0 0 8px 0;
      color: #303133;
      font-size: 24px;
      font-weight: 600;
    }
    
    .page-description {
      margin: 0;
      color: #909399;
      font-size: 14px;
    }
  }

  .filter-section {
    margin-bottom: 20px;
    
    .filter-content {
      display: flex;
      flex-wrap: wrap;
      gap: 20px;
      align-items: center;
      
      .filter-item {
        display: flex;
        align-items: center;
        gap: 8px;
        
        label {
          font-weight: 500;
          color: #606266;
          white-space: nowrap;
        }
      }
    }
    
    .account-option,
    .friend-option {
      display: flex;
      align-items: center;
      gap: 8px;
      
      .account-avatar,
      .friend-avatar {
        flex-shrink: 0;
      }
    }
    
    .empty-data {
      text-align: center;
      padding: 10px 0;
      color: #909399;
    }
  }

  .qa-list-section {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      .qa-count {
        font-size: 14px;
        color: #909399;
      }
    }
    
    .loading-container,
    .empty-container {
      display: flex;
      justify-content: center;
      align-items: center;
      min-height: 200px;
    }
    
    .qa-content {
      .qa-text {
        white-space: normal;
        word-break: break-word;
        line-height: 1.5;
      }
      .meta-tags {
        display: flex;
        gap: 6px;
        margin-bottom: 6px;
        flex-wrap: wrap;
      }
      .qa-lines {
        .line {
          margin-bottom: 4px;
          .label {
            color: #606266;
            font-weight: 500;
            margin-right: 4px;
          }
        }
      }
    }
    
    .action-buttons {
      display: flex;
      gap: 8px;
      align-items: center;
    }
    
    .pagination-container {
      display: flex;
      justify-content: center;
      margin-top: 20px;
      padding: 20px 0;
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .material-library-container {
    padding: 10px;
    
    .filter-section {
      .filter-content {
        flex-direction: column;
        align-items: stretch;
        
        .filter-item {
          flex-direction: column;
          align-items: stretch;
          
          label {
            margin-bottom: 4px;
          }
        }
      }
    }
  }
}
</style>